# coding=utf-8
__author__ = u'武海峰'
# coding=utf-8
import json
from django.http import HttpResponse
from django.shortcuts import render_to_response
from .models import Branch, User, Log, Project, NickName
import datetime
import time


# Create your views here.
# 首页列表显示
def index(request):
    log = Log.objects.all()[:10]
    return render_to_response('index.html', {"logs": log})


# 跳转到添加项目页面
def create_html(request):
    return render_to_response('create.html')


# 跳到总数页面
def total_data_html(request):
    project = Project.objects.all()
    return render_to_response('histogram.html', {"project": project})


# 各人总数据柱状图
def test(request):
    add, update, remove, nicks = [], [], [], []
    nick_list = NickName.objects.all()
    for nick in nick_list:
        nickname = nick.id
        total_add, total_update, total_remove = 0, 0, 0
        log = Log.objects.all().filter(author__nickname=nickname)
        for i in range(len(log)):
            total_add = total_add + log[i].add
            total_update = total_update + log[i].files
            total_remove = total_remove + log[i].remove
        nicks.append(nick.nickname)
        add.append(total_add)
        update.append(total_update)
        remove.append(total_remove)
    return HttpResponse(json.dumps({"users": nicks, "add": add, "update": update, "remove": remove}),
                        content_type=u'application/json')


# 某个周期内每个人总数据
def every_total(request):
    users, add, files, remove = [], [], [], []
    from_date = request.GET.get('from_date')
    to_date = request.GET.get('to_date')
    project_id = request.GET.get('project').split(',')
    query = Log.objects.all()
    if from_date:
        from_date = datetime.datetime.strptime(from_date, "%Y-%m-%d").date()
        query = query.filter(datetime__gte=from_date)
    if to_date:
        to_date = datetime.datetime.strptime(to_date, "%Y-%m-%d").date()
        query = query.filter(datetime__lte=to_date)
    nick_list = NickName.objects.all()

    for nick in nick_list:
        nick_id = nick.id
        total_add, total_files, total_remove = 0, 0, 0
        query2 = query.filter(author__nickname=nick_id)
        for p_id in project_id:
            project_add = 0
            project_remove = 0
            project_files = 0
            query3 = query2.filter(branch__project__id=p_id)
            for log in query3:
                project_add = project_add + log.add
                project_files = project_files + log.files
                project_remove = project_remove + log.remove
            total_add = total_add + project_add
            total_files = total_files + project_files
            total_remove = total_remove + project_remove
        users.append(nick.nickname)
        add.append(total_add)
        files.append(total_files)
        remove.append(total_remove)
    return HttpResponse(json.dumps({"users": users, "add": add, "files": files, "remove": remove}),
                        content_type=u'application/json')


# 跳转到某个周期每个人每天总数页面折线图显示
def every_total_html(request):
    project = Project.objects.all()
    nickname = NickName.objects.all()
    return render_to_response('line_chart.html',
                              {"project": project, "nickname": nickname})


# 某个周期内每个人每天添加行数折线图
def everyday_everyone(request):
    date_list = []
    data = []
    add_line_number = '添加行数'
    from_date = request.GET.get('from_date')
    to_date = request.GET.get('to_date')
    pro_id = request.GET.get("project").split(',')
    users = request.GET.get("users").split(",")
    logquery = Log.objects.all()

    if from_date:
        from_date = datetime.datetime.strptime(from_date, "%Y-%m-%d").date()
        logquery = logquery.filter(datetime__gte=from_date)
    if to_date:
        to_date = datetime.datetime.strptime(to_date, "%Y-%m-%d").date() + datetime.timedelta(1)
        logquery = logquery.filter(datetime__lte=to_date)

    curr_date = from_date
    while curr_date != to_date:
        date_list.append("%04d%02d%02d" % (curr_date.year, curr_date.month, curr_date.day))
        curr_date += datetime.timedelta(1)

    nick_dict = {}
    for d in date_list:
        for nick in NickName.objects.filter(id__in=users):
            total_add = 0
            user_logquery = logquery.filter(author__nickname=nick)
            if not nick_dict.has_key(nick.nickname):
                nick_dict[nick.nickname] = []
            for p_id in pro_id:
                project_add = 0
                query = user_logquery.filter(branch__project__id=p_id)
                for log in query:
                    date = log.datetime.date()
                    date = date.strftime("%Y%m%d")
                    if date == d:
                        project_add = project_add + log.add
                total_add = total_add + project_add
            nick_dict[nick.nickname].append(total_add)
    for k, v in nick_dict.items():
        data.append({"name": "%s" % k, "data": v})

    return HttpResponse(
        json.dumps({"data": data, "date_list": date_list, 'add_line_number': add_line_number}),
        content_type=u'application/json')


# 某个周期内每个人每天修改文件数总数折线图
def everyday_everyone_files(request):
    date_list, data, nick_dict = [], [], {}
    update_line_number = '修改文件数'
    from_date = request.GET.get('from_date')
    to_date = request.GET.get('to_date')
    project_id = request.GET.get('project').split(',')
    user_id = request.GET.get('users').split(',')
    query = Log.objects.all()
    if from_date:
        from_date = datetime.datetime.strptime(from_date, "%Y-%m-%d").date()
        query = query.filter(datetime__gte=from_date)
    if to_date:
        to_date = datetime.datetime.strptime(to_date, "%Y-%m-%d").date() + datetime.timedelta(1)
        query = query.filter(datetime__lte=to_date)

    curr_date = from_date
    while curr_date != to_date:
        date_list.append("%04d%02d%02d" % (curr_date.year, curr_date.month, curr_date.day))
        curr_date += datetime.timedelta(1)

    for d in date_list:
        for nick in NickName.objects.filter(id__in=user_id):
            total_files = 0
            query2 = query.filter(author__nickname=nick)
            if not nick_dict.has_key(nick.nickname):
                nick_dict[nick.nickname] = []
            for p_id in project_id:
                project_files = 0
                query3 = query2.filter(branch__project__id=p_id)
                for log in query3:
                    date = log.datetime.date()
                    if date.strftime('%Y%m%d') == d:
                        project_files = project_files + log.files
                total_files = total_files + project_files
            nick_dict[nick.nickname].append(total_files)
    for k, v in nick_dict.items():
        data.append({"name": "%s" % k, "data": v})
    return HttpResponse(
        json.dumps({"data": data, "date_list": date_list, 'update': update_line_number}),
        content_type=u'application/json')


# 某个周期内每个人每天移除总行数总数折线图
def everyday_everyone_remove(request):
    date_list, data = [], []
    remove_line_number = '删除行数'
    from_date = request.GET.get('from_date')
    to_date = request.GET.get('to_date')
    pro_id = request.GET.get("project").split(',')
    users = request.GET.get("users").split(",")
    logquery = Log.objects.all()

    if from_date:
        from_date = datetime.datetime.strptime(from_date, "%Y-%m-%d").date()
        logquery = logquery.filter(datetime__gte=from_date)

    if to_date:
        to_date = datetime.datetime.strptime(to_date, "%Y-%m-%d").date() + datetime.timedelta(1)
        logquery = logquery.filter(datetime__lte=to_date)

    curr_date = from_date
    while curr_date != to_date:
        date_list.append("%04d%02d%02d" % (curr_date.year, curr_date.month, curr_date.day))
        curr_date += datetime.timedelta(1)

    nick_dict = {}
    for d in date_list:
        for nick in NickName.objects.filter(id__in=users):
            total_remove = 0
            query = logquery.filter(author__nickname=nick)
            if not nick_dict.has_key(nick.nickname):
                nick_dict[nick.nickname] = []

            for p_id in pro_id:
                project_remove = 0
                query2 = query.filter(branch__project__id=p_id)
                for log in query2:
                    date = log.datetime.date()
                    date = date.strftime("%Y%m%d")
                    if date == d:
                        project_remove = project_remove + log.remove
                total_remove = total_remove + project_remove
            nick_dict[nick.nickname].append(total_remove)
    for k, v in nick_dict.items():
        data.append({"name": "%s" % k, "data": v})
    return HttpResponse(
        json.dumps({"data": data, "date_list": date_list, 'remove': remove_line_number}),
        content_type=u'application/json')


# 跳转到修改项目页面
def update_html(request):
    git_project = Project.objects.all()
    return render_to_response('update_git.html', {"git_project": git_project})


def update_git_info(request):
    name = request.GET.get('pro_name')
    p_dict = request.GET.get('dict')
    note = request.GET.get('note')
    git_project = Project.objects.all()
    project = git_project.get(pro_name=name)
    project.dict = p_dict
    project.note = note
    project.save()

    message = "修改成功"
    return HttpResponse(json.dumps({"message": message}), content_type=u'application/json')
